﻿using AutoMapper;
using Enum;
using MediatR;
using Practice.Common.Domains;
using Practice.Common.Dto;
using Practice.Common.Infrastructure.Interfaces;

namespace Practice.API.Application.Commands.Roles
{
    public class RoleCreateHandler : IRequestHandler<RoleCreateCommand, Result>
    {
        public readonly IBaseRepository<Role> RolRepository;
        public readonly IBaseRepository<RolePermission> RolePermissionRepository;
        public readonly IMapper _mapper;

        public RoleCreateHandler(IBaseRepository<Role> rolRepository, IBaseRepository<RolePermission> rolePermissionRepository, IMapper mapper)
        {
            RolRepository = rolRepository;
            RolePermissionRepository = rolePermissionRepository;
            _mapper = mapper;
        }

        public async Task<Result> Handle(RoleCreateCommand request, CancellationToken cancellationToken)
        {
          
            var result = new Result() { Code=(int)CommonEnumCode.Added };
            try
            {
                var res = new Role() { 
                    RoleName = request.RoleName,
                };
                RolRepository.Add(res);
                var res1 = new RolePermission()
                {
                    RoleId = res.RoleId,
                    PermissionId = request.PermissionId,
                    PermissionMassage = request.PermissionMassage,
                    CreateTime= DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
            };
                RolePermissionRepository.Add(res1);
                if (res != null)
                {
                    result.Code = (int)CommonEnumCode.Success;
                }
                
            }
            catch (Exception)
            {

                result.Msg = "角色添加失败";
            }
            return result;
        }
    }
}
